package com.cx.util.device;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 时间帮助类
 */
public class TimeHelper {
    /**
     *  simple 2001-07-04 12:08
     */
    public static final String TIME_FORMAT_YY_MM_MM = "yyyy-MM-dd HH:mm";
    /**
     * simple 2001-07-04 12:08:56
     */
    public static final String TIME_FORMAT_YY_SS = "yyyy-MM-dd HH:mm:ss";
    /**
     * simple 2001-07-04
     */
    public static final String TIME_FORMAT_YY_DD = "yyyy-MM-dd";
    /**
     * simple 2001-07
     */
    public static final String TIME_FORMAT_YY_MM = "yyyy-MM";
    /**
     * simple 2001-07-04T12:08:56.235-0700
     */
    public static final String TIME_FORMAT_YY_SSSZ = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    /**
     * simple 2001-07-04T12:08:56.235-07:00
     */
    public static final String TIME_FORMAT_YY_SSSXXX = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    /**
     * 将时间戳转为指定的格式
     *
     * @param time   时间戳(milliseconds)
     * @param format 转换格式
     * @return 指定的格式
     */
    public static String stamp2String(long time, String format) {
        Date date = new Date();
        date.setTime(time);
        SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.getDefault());
        return dateFormat.format(date);

    }



    /**
     * 将指定的格式的时间转为时间戳
     *
     * @param timeString   时间
     * @param format 转换格式
     * @return 时间戳(milliseconds)
     */
    public static long stringToStamp(String timeString, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.getDefault());
        return dateFormat.parse(timeString, new ParsePosition(0)).getTime();
    }

    /**
     * 将 {@code "yyyy-MM-dd HH:mm:ss"} 时间格式转为时间戳
     *
     * @param timeString 2001-07-04 12:08:56 转时间戳
     * @return  时间戳(milliseconds)
     */
    public static long stringToStamp(String timeString) {
        return stringToStamp(timeString, TIME_FORMAT_YY_SS);
    }
    public static String getY2Min(long time) {
        return stamp2String(time, TIME_FORMAT_YY_MM_MM);
    }

    public static String getY2Day(long time) {
        return stamp2String(time, TIME_FORMAT_YY_DD);
    }
}